package isquirrel.util;

import isquirrel.UserManager;
import isquirrel.beans.User;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpSession;

public class Utilities {
	
	/**
	 * Hashes a given password using the MD5 algorithm, for storing in the user's database.
	 * @param password  The password to hash.
	 * @return The hashed password.
	 */
	public static String hashPassword(String password) {
		//Random rnd = new Random(new Date().getTime());
		
		//String salt = "" + rnd.nextInt();	
		String to_be_encoded = password;
		
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(to_be_encoded.getBytes());
			BigInteger hash = new BigInteger(1, md5.digest());
			to_be_encoded = hash.toString(16);
		} catch (NoSuchAlgorithmException nsae) {
			System.err.print(nsae);
		}
		return to_be_encoded;
	}
	
	/**
	 * Creates a unique token for each user. The uniqueness of the token is guaranteed by the algorithm seed, which is 
	 * the time and date of creation.
	 * @param username  The username of the user.
	 * @return The token. 
	 */
	public static String createToken(String username){
	
		Random rnd = new Random(new Date().getTime());
		
		String salt = "" + rnd.nextInt();
		String to_be_encoded = new Date().toString() + username + salt;
	  
		try{
	 
		  MessageDigest md = MessageDigest.getInstance("SHA"); 
	      md.update(to_be_encoded.getBytes("UTF-8"));
	      BigInteger hash = new BigInteger(1, md.digest());
		  to_be_encoded = hash.toString(32);
		  
	    } catch (NoSuchAlgorithmException nsae) {
			System.err.print(nsae);
		} catch (UnsupportedEncodingException uee) {
			System.err.print(uee);
		} catch (Exception e){
			System.err.print(e);
		}
		
		return to_be_encoded;
	}
	
	public static String createBookmarklet(String url){
				
		String oh_god_code = "";
				
		byte[] bytes = null;
		try {
			bytes = url.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			return "Eerrr";
		}
		
		for (int i=0; i < bytes.length; i++) {
		    oh_god_code += "\\x" +
		          Integer.toString( ( bytes[i] & 0xff ) + 0x100, 16).substring(1);
		  }
	
		return oh_god_code;
	}
	
	public static String generateUniqueString(int noOfCharacters) {	
        
		char[] printableAscii = new char[]{'!', '\"', '#', '$', '%', '(', ')', '*', '+', '-', '.', '/', '\'',
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':', '<', '=', '>', '?', '@',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
		
        SecureRandom random = new SecureRandom();
		random.setSeed(new Date().getTime());
		String unique = "";
		for (int i = 0; i<noOfCharacters; i++) {
			int n = random.nextInt(printableAscii.length);
			unique += printableAscii[n];
		}
		return unique;
	}
	
	public static User getSessionUser(HttpSession session) {	
		if (isVisitorLoggedIn(session)) {
			String username = (String) session.getAttribute("user");		
			return UserManager.getUser(username);
		}
		return null;
	}

/*	
	@Deprecated
	public static User getSessionUser(HttpSession session) {
		if (session.getAttribute("UserBean") == null) {
			String username = (String) session.getAttribute("user");
			session.setAttribute("UserBean", UserManager.getUser(username));
		}
		return (User) session.getAttribute("UserBean");
		
	}
*/	
	public static boolean isVisitorLoggedIn(HttpSession session) {
		boolean isLoggedIn = false;
		if (session.getAttribute("user") != null) {
			isLoggedIn = true;
		}
		return isLoggedIn;
	}

	private enum months {
		January,
		February, 
		March, 
		April, 
		May, 
		June, 
		July, 
		August, 
		September,
		October,
		November, 
		December
	};
	public static int convertMonthStringtoMonthInteger(String monthString) {
		int monthNumber = -1;
		switch (months.valueOf(monthString)) {
			case January: monthNumber = 1; break;
			case February: monthNumber = 2; break;
			case March: monthNumber = 3; break;
			case April: monthNumber = 4; break;
			case May: monthNumber = 5; break;
			case June: monthNumber = 6; break;
			case July: monthNumber = 7; break;
			case August: monthNumber = 8; break;
			case September: monthNumber = 9; break;
			case October: monthNumber = 10; break;
			case November: monthNumber = 11; break;
			case December: monthNumber = 12; break;
		}
		return monthNumber;
	}
	
	public static Date convertStringDatetoDateObject(String date, String dateFormat) {
		SimpleDateFormat f = new SimpleDateFormat(dateFormat);
		Date d = null;
		try {
			d = f.parse(date);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		return d;
	}
}
